package com.hzsai.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * hzsai 2019/8/1
 * usage:
 **/
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    /**
     * 获取线程池
     * @return
     */
    @Nullable
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10); // 核心线程数
        taskExecutor.setMaxPoolSize(30); // 最大线程数
        taskExecutor.setQueueCapacity(2000); // 队列容量
        taskExecutor.initialize(); // 初始化
        return taskExecutor;
    }

    /**
     * 异步异常处理
     * @return
     */
    @Nullable
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    }
}
